/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.persistence.entity;

import com.je.bpm.engine.impl.ModelQueryImpl;
import com.je.bpm.engine.impl.Page;
import com.je.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import com.je.bpm.engine.impl.persistence.entity.data.DataManager;
import com.je.bpm.engine.impl.persistence.entity.data.ModelDataManager;
import com.je.bpm.engine.repository.Model;

import java.util.List;
import java.util.Map;

public class ModelEntityManagerImpl extends AbstractEntityManager<ModelEntity> implements ModelEntityManager {

    protected ModelDataManager modelDataManager;

    public ModelEntityManagerImpl(ProcessEngineConfigurationImpl processEngineConfiguration, ModelDataManager modelDataManager) {
        super(processEngineConfiguration);
        this.modelDataManager = modelDataManager;
    }

    @Override
    protected DataManager<ModelEntity> getDataManager() {
        return modelDataManager;
    }

    @Override
    public ModelEntity findById(String entityId) {
        return modelDataManager.findById(entityId);
    }

    @Override
    public void insert(ModelEntity model) {
        ((ModelEntity) model).setCreateTime(getClock().getCurrentTime());
        ((ModelEntity) model).setLastUpdateTime(getClock().getCurrentTime());

        super.insert(model);
    }

    @Override
    public void updateModel(ModelEntity updatedModel) {
        updatedModel.setLastUpdateTime(getClock().getCurrentTime());
        update(updatedModel);
    }

    @Override
    public void delete(String modelId) {
        ModelEntity modelEntity = findById(modelId);
        super.delete(modelEntity);
        deleteEditorSource(modelEntity);
        deleteEditorSourceExtra(modelEntity);
    }

    @Override
    public void insertEditorSourceForModel(String modelId, byte[] modelSource) {
        ModelEntity model = findById(modelId);
        if (model != null) {
            ByteArrayRef ref = new ByteArrayRef(model.getEditorSourceValueId());
            ref.setValue("source", modelSource);

            if (model.getEditorSourceValueId() == null) {
                model.setEditorSourceValueId(ref.getId());
                updateModel(model);
            }
        }
    }

    @Override
    public void deleteEditorSource(ModelEntity model) {
        if (model.getEditorSourceValueId() != null) {
            ByteArrayRef ref = new ByteArrayRef(model.getEditorSourceValueId());
            ref.delete();
        }
    }

    @Override
    public void deleteEditorSourceExtra(ModelEntity model) {
        if (model.getEditorSourceExtraValueId() != null) {
            ByteArrayRef ref = new ByteArrayRef(model.getEditorSourceExtraValueId());
            ref.delete();
        }
    }

    @Override
    public void insertEditorSourceExtraForModel(String modelId, byte[] modelSource) {
        ModelEntity model = findById(modelId);
        if (model != null) {
            ByteArrayRef ref = new ByteArrayRef(model.getEditorSourceExtraValueId());
            ref.setValue("source-extra", modelSource);

            if (model.getEditorSourceExtraValueId() == null) {
                model.setEditorSourceExtraValueId(ref.getId());
                updateModel(model);
            }
        }
    }

    @Override
    public List<Model> findModelsByQueryCriteria(ModelQueryImpl query, Page page) {
        return modelDataManager.findModelsByQueryCriteria(query, page);
    }

    @Override
    public long findModelCountByQueryCriteria(ModelQueryImpl query) {
        return modelDataManager.findModelCountByQueryCriteria(query);
    }

    @Override
    public byte[] findEditorSourceByModelId(String modelId) {
        ModelEntity model = findById(modelId);
        if (model == null || model.getEditorSourceValueId() == null) {
            return null;
        }

        ByteArrayRef ref = new ByteArrayRef(model.getEditorSourceValueId());
        return ref.getBytes();
    }

    @Override
    public byte[] findEditorSourceExtraByModelId(String modelId) {
        ModelEntity model = findById(modelId);
        if (model == null || model.getEditorSourceExtraValueId() == null) {
            return null;
        }

        ByteArrayRef ref = new ByteArrayRef(model.getEditorSourceExtraValueId());
        return ref.getBytes();
    }

    @Override
    public List<Model> findModelsByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) {
        return modelDataManager.findModelsByNativeQuery(parameterMap, firstResult, maxResults);
    }

    @Override
    public List<Model> findModelsByMultipleConditionsOrQueryCriteria(ModelQueryImpl query, Page page) {
        return modelDataManager.findModelsByMultipleConditionsOrQueryCriteria(query, page);
    }

    @Override
    public long findModelCountByNativeQuery(Map<String, Object> parameterMap) {
        return modelDataManager.findModelCountByNativeQuery(parameterMap);
    }

    public ModelDataManager getModelDataManager() {
        return modelDataManager;
    }

    public void setModelDataManager(ModelDataManager modelDataManager) {
        this.modelDataManager = modelDataManager;
    }

}
